#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
|===== Conference Bot Plugin ============
|=Game Commands
|===== By: ==============================
|= Patrick Kennedy
|===== Current Version: =================
|= 1.0
|===== Description: =========================================
|= Game related commands.
|===== Additional Comments: =================================
|= 
|============================================================"""
import random
import time

from utils import *

def init(bot):
	bot.addCommand("math", cmd_math)
	bot.addTimer(1, timer_math, type = "minutes")
	bot.addHook('message', hook_math)
	bot.games['math'] = {'running':False, 'questions':'1 + 1', 'scores':{}}
	global tries_max
	tries_max = 20
	
def unload(bot):
	bot.removeCommand("math")
	bot.removeTimer('timer_math')
	bot.removeHook('hook_math')

def cmd_math(bot, user, command):
	"""Get the current question.
Usage: )math [<command>]

Commands:
start - Start the game.
new - Cycle to a new question.
stop - Stop the game.

Note: Only admins and mods can start and stop the game."""
	if not command:
		if isrunning(bot):
			bot.sys(user, "The current question is:\n%s" % getquestion())
			return
		bot.error(user, "The Math Game isn't running.")
	elif not ismod(user):
		bot.error(user, cmd_math.__doc__)
	else:
		if command == "start":
			if isrunning(bot):
				bot.error(user, "The game is already running.")
				return
			start(bot)
			reset(bot)
			bot.systoall("The Math Game has been started by %s" % getdisplayname(user), log = True)
		elif command == "new":
			reset(bot)
		elif command == "stop":
			if not isrunning(bot):
				bot.error(user, "The game isn't running.")
				return
			stop(bot)
			bot.systoall("The Math Game has been ended by %s" % getdisplayname(user), log = True)

		else:
			bot.error(user, "Unknown command option.")

def timer_math(bot):
	if isrunning(bot):
		newquestion()
		bot.systoall("The question for the Math Game is:\n%s" % (getquestion()))
			
def hook_math(bot, answer):
	user, answer = answer
	if not isrunning(bot):
		return False
	if ' ' in answer:
		answer = answer[:answer.find(' ')]
	try:
		if iscorrect(int(answer)):
			bot.systoall("<%s> got the correct answer (%s) to the question (%s) in %s seconds!\n*** A new round will start shortly." % (getdisplayname(user), answer, getquestion(), gettime(bot)), log = True)
			reset(bot, random.randint(10, 15))
			return True
	except:
		return False
	
			
def randomsign(number = 0):
	number = number or random.randint(1,4)
	if number == 1:
		return '+'
	elif number == 2:
		return '-'
	elif number == 3:
		return '*'
	elif number == 4:
		return '/'
	else:
		return '+'

def roll(min = 0, max = 24):
	return [random.randint(0,24) for i in range(2)]
		
def iscorrect(answer):
	return int(eval(question)) == answer

def isrunning(bot):
	return bot.games["math"]["running"]
	
def setstate(bot, state):
	bot.games["math"]["running"] = state

def start(bot):
	setstate(bot, True)
def stop(bot):
	setstate(bot, False)
def reset(bot, offset = 0):
	timer = bot.timerevents[timer_math]
	bot.timerevents[timer_math][1] = ((timer[1] - ((timer[1] + timer[0]) - time.time())) + offset)
	
def newquestion(sign = 0):
	sign = randomsign(sign)
	numbers = roll()
	if sign == '-' and numbers[0] < numbers[1]:
		numbers.reverse()
	elif sign == '/':
		tries = 0
		answer = float(numbers[0]) / float(numbers[1])
		while tries > tries_max or (answer - int(answer)) != 0.0:
			if 0 in numbers:
				numbers = roll()
			answer = float(numbers[0]) / float(numbers[1])
			if (answer - int(answer)) == 0.0 and numbers[0] != answer != 1:
				break
			tries += 1
			numbers = roll()
	elif sign == '*':
		while (numbers[0] * numbers[1]) > 100:
			numbers = roll(1, 12)
	
	global question
	question = '%s %s %s' % (numbers[0], sign, numbers[1])
	
def getquestion():
	return question

def gettime(bot):
	return int(round(time.time() - bot.timerevents[timer_math][1]))
	
	
def setscore(user): pass
